import os

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding



import base64

def base64_encode(input_bytes):
    encoded_bytes = base64.b64encode(input_bytes)
    return encoded_bytes.decode('utf-8')

def base64_decode(encoded_string):
    decoded_bytes = base64.b64decode(encoded_string)
    return decoded_bytes

from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding

def aes_encrypt(key, iv, plaintext):
    # 使用PKCS7填充
    padder = padding.PKCS7(128).padder()
    padded_data = padder.update(plaintext) + padder.finalize()

    # 创建AES加密器
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    encryptor = cipher.encryptor()

    # 加密数据
    ciphertext = encryptor.update(padded_data) + encryptor.finalize()
    return ciphertext


def aes_decrypt(key, iv, ciphertext):
    # 创建AES解密器
    cipher = Cipher(algorithms.AES(key), modes.CFB(iv), backend=default_backend())
    decryptor = cipher.decryptor()

    # 解密数据
    padded_data = decryptor.update(ciphertext) + decryptor.finalize()

    # 去除填充
    unpadder = padding.PKCS7(128).unpadder()
    plaintext = unpadder.update(padded_data) + unpadder.finalize()
    return plaintext




# if __name__ == '__main__':

    # 生成随机的16字节密钥
    # key = os.urandom(16)
    # key = b'1234567890ABCDEF'
    # iv = os.urandom(16)  # 随机生成16字节的IV
    # iv = b'1234567890ABCDEF'  # 随机生成16字节的IV

    # key = b'12A#GH)90AfjdF&s'
    # iv = b'947owi9@PI49#e^h'  # 指定16字节的IV
    #
    # # 需要加密的数据
    # data = bytes('{"name": "test", "uuid": "032a467b-c6d0-4de2-9bd9-57817030e9cc", "time": "1699929355000","random": "9567"}',encoding="utf-8")
    # result1 = aes_encrypt(key,iv,data)
    # print(result1)
    # result2 = base64_encode(result1)
    # print(result2)


    # result3 = base64_decode("wVtmQ/lfpouD0eacAnQEinbr8zf8wTxodqQhCq4IEzyKOHXT6krCI0BeoBh3EQCQeieI3OJzoAsfIbQpqaOvwWK8k4XNS9ZRsMlBjoEja9okU+7ZlYLLuCs6nsJSyJm3JvUZYgoG8Lk6FZbng9Stdw==")
    # print(result3)
    # result4 = aes_decrypt(key,iv,result3)
    # print(result4)










